﻿using GloboTicketAdmin.Mobile.Common;
using GloboTicketAdmin.Mobile.Models;
using GloboTicketAdmin.Mobile.ViewModels;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Json;
using System.Text;
using System.Text.Json;
using System.Text.Json.Serialization;
using System.Threading.Tasks;

namespace GloboTicketAdmin.Mobile.Repositories
{
    public class EventRepository : IEventRepository
    {
        private readonly IHttpClientFactory _httpClientFactory;

        public EventRepository(IHttpClientFactory httpClientFactory)
        {
            _httpClientFactory = httpClientFactory;
        }

        public async Task<bool> CreateEvent(EventModel model)
        {
            using HttpClient client = _httpClientFactory.CreateClient("GloboTicketAdminApiClient");
            try
            {
                var response = await client.PostAsJsonAsync<EventModel>($"api/events",model);
                var taskResult= response.Content.ReadFromJsonAsync<ApiResponse<EventModel>>();
                return taskResult.Result.Success;
            }
            catch (Exception ex)
            {
                // Log the exception or handle it as needed
                return false;
            }
        }

        public async Task<bool> DeleteEvent(Guid id)
        {
            using HttpClient client = _httpClientFactory.CreateClient("GloboTicketAdminApiClient");
            try
            {
                var response = await client.DeleteAsync($"api/events/{id}");
                var taskResult = response.Content.ReadFromJsonAsync<ApiResponse<EventModel>>();
                return taskResult.Result.Success;
            }
            catch (Exception ex)
            {
                return false;
            }
        }

        public async Task<bool> EditEvent(EventModel model)
        {
            using HttpClient client = _httpClientFactory.CreateClient("GloboTicketAdminApiClient");
            try
            {
                var response = await client.PutAsJsonAsync<EventModel>($"api/events/{model.Id}", model);
                var taskResult = response.Content.ReadFromJsonAsync<ApiResponse<EventModel>>();
                return taskResult.Result.Success;
            }
            catch (Exception ex)
            {
                // Log the exception or handle it as needed
                return false;
            }
        }

        public async Task<EventModel?> GetEvent(Guid id)
        {
            using HttpClient client = _httpClientFactory.CreateClient("GloboTicketAdminApiClient");
            try 
            {
                //EventModel? @event= await client.GetFromJsonAsync<EventModel>(
                //    $"api/events/{id}",
                //    new JsonSerializerOptions(JsonSerializerDefaults.Web)
                //    );
                //return @event;
                var response = await client.GetFromJsonAsync<ApiResponse<EventModel>>($"api/events/{id}");
                return response != null ? response.Data : new EventModel();
            }
            catch (Exception ex)
            {
                // Log the exception or handle it as needed
                return null;
            }
        }

        public async Task<List<EventModel>> GetEvents()
        {
            using HttpClient client = _httpClientFactory.CreateClient("GloboTicketAdminApiClient");
            try 
            {
                //List<EventModel>? events = await client.GetFromJsonAsync<List<EventModel>>(
                //    $"api/events",
                //    new JsonSerializerOptions(JsonSerializerDefaults.Web)
                //    );
                var options = new JsonSerializerOptions(JsonSerializerDefaults.Web)
                {
                    Converters = { new JsonStringEnumConverter() }, // 启用字符串与枚举的转换
                    PropertyNameCaseInsensitive = true // 忽略大小写（可选）
                };
                var response = await client.GetFromJsonAsync<ApiResponse<List<EventModel>>>($"api/events", options);
                return response != null ? response.Data : new List<EventModel>();
            }
            catch (Exception ex)
            {
                // Log the exception or handle it as needed
                return new List<EventModel>();
            }
        }

        public async Task<bool> UpdateStatus(Guid id, EventStatusModel status)
        {
            using HttpClient client = _httpClientFactory.CreateClient("GloboTicketAdminApiClient");
            try
            {
                var json = JsonSerializer.Serialize(status);
                var content = new StringContent(json, Encoding.UTF8, "application/json");
                var response = await client.PutAsync($"api/events/{id}/status", content);
                if (response.IsSuccessStatusCode)
                {
                    return true;
                }
                else
                {
                    // Optionally log the error or handle it as needed
                    return false;
                }
            }
            catch (Exception ex)
            {
                return false;
            }
        }
    }
}
